<?php
require_once 'common.php';

$user_cell_xy = playground::get_user_last_create_cell_xy(user::getId());
if ($user_cell_xy && $user_cell_xy['x'] && $user_cell_xy['y'])
{
	$user_cell_x = $user_cell_xy['x'];
	$user_cell_y = $user_cell_xy['y'];
}
else
{
	$user_cell_x = MAP_SIZE/2;
	$user_cell_y = MAP_SIZE/2;
}
?>

var map_size = <?php echo MAP_SIZE; ?>;
var mini_map_size = <?php echo MINI_MAP_SIZE; ?>;
var navi_scale = (map_size/mini_map_size);

var cell_size = <?php echo CELL_SIZE; ?>;
var cell_count_of_brick_side = <?php echo CELL_COUNT_OF_BRICK_SIDE; ?>;
var brick_size = cell_size*cell_count_of_brick_side;

//地图初始化位置
var map_x = <?php echo $user_cell_x; ?>*cell_size;
var map_y = <?php echo $user_cell_y; ?>*cell_size;

var win_width = $(window).width();
var win_height = $(window).height();


$(function($) {
	navigateToCellXY = function(x, y)
	{
		$('#play_ground_stage').html('');
		map_x = x*cell_size;
		map_y = y*cell_size;
		draw_map(0, 0);
	}
	
	$('#mini_map_min_max').bind('click', function(ev){
		if ($('#mini_map').width()==map_size/navi_scale)
		{
			mini_map_size = map_size*2/navi_scale;
		}
		else if ($('#mini_map').width()==map_size*2/navi_scale)
		{
			mini_map_size = 0;
		}
		else
		{
			mini_map_size =  map_size/navi_scale;
		}
		
		//mini_map_size = ($('#mini_map').width()==map_size/navi_scale) ? map_size*2/navi_scale : map_size/navi_scale;
		$('#mini_map')
			.animate({width:mini_map_size, height:mini_map_size}, 300)
			.css({'background-image':'url(port/minimap.php?size='+mini_map_size+')'})
		draw_map(0, 0);
	});
	
	var transparent_css_data = {
		border:'none',
		'color':'white',
		'background':'#333',
		'text-align':'center',
		'width':'400px',
		padding:'20px',
	}

	logout = function()
	{
		$.post("/port/logout.user.php", null, function(data){
				draw_playground_tool_box();
				$('#mini_map').css({
					'background-image':'url(port/minimap.php?' + Math.random() + ')'
				});
			}, "json");
	}
		
	var tool_box_onshow = true;
	toggle_tool_box = function()
	{
		var button = $('#button_toggle_tool_box');
		if (tool_box_onshow)
		{
			button.attr('value', '还原 <<');
			var offset = button.offset();
			var dist = $(window).width()-offset.left-40;
			$('#playground_tool_box')
				.animate({right:-dist}, 300);
		}
		else
		{
			$('#button_toggle_tool_box').attr('value', '隐藏 >>');
			$('#playground_tool_box')
				.animate({right:0}, 300);
		}
		tool_box_onshow = !tool_box_onshow;
	}
	
	draw_playground_tool_box = function()
	{
		s = '<input type=button style="font-size:12px" value="隐藏 >>" id="button_toggle_tool_box" onclick="toggle_tool_box()"/>';
		s = '';
		
		if ($.cookie('user_logged'))
		{
			s += '<input type=button value="'+$.cookie('user_nickname').replace('+', ' ')+' 退出" onclick="logout()" />'
		}
		else
		{
			s += '<input type=button value="注册一个账户填方格" onclick="show_register_form()" />';
			s += '<input type=button value="我有账号我登录" onclick="show_login_form()" />';
		}
		
		s += '<input type=button value="返回weekdo首页" onclick="document.location.href=\'/\'"/>';
		s += '<input type=button value="帮助" style="font-weight:bold;" onclick="show_playground_help()" />';
		$('#playground_tool_box').html(s);

	}
	draw_playground_tool_box();
	
	
	do_login = function()
	{
		var user_login = ($("#login_form input[name='login']").attr('value'));
		var user_passwd = ($("#login_form input[name='passwd']").attr('value'));
		//alert (user_nickname+', '+user_passwd);
		//return false;

		$.post("/port/login.user.php", {
				"login" : user_login,
				"passwd" : user_passwd
			}, function(data){
				if (data && data.result)
				{
					$('#login_error_message')
						.html('登录成功！可以开始占领你自己的小方块啦~')
						.css({'color':'green'});
					setTimeout(function(){
						$.unblockUI();
					}, 1200);
					$.growlUI('登录成功！可以点击占领属于你自己的小方块啦~'); 
				}
				else
				{
					$('#login_error_message')
						.html('登录失败，请检查您的登录名或密码')
						.css({'color':'red'});
				}
				$('#mini_map').css({
					'background-image':'url(port/minimap.php?' + Math.random() + ')'
				});
				draw_playground_tool_box();
			}, "json");
	}
	
	$("#login_form input[name='passwd']").keydown(function(e) {
		if(e.keyCode == 13) { // enter
			do_login();
		}
	});

	$('#login_form_submit').bind('click', function(){
		do_login();
	});

	show_login_form = function(s)
	{
		if (s)
		{
			$('#login_error_message')
				.html(s)
				.css({'color':'yellow'});
		}
		$.blockUI({ message: $('#login_form'), css:transparent_css_data});
	}
	
		
	do_register = function()
	{
		var user_email = ($("#register_form input[name='user_email']").attr('value'));
		var user_nickname = ($("#register_form input[name='user_nickname']").attr('value'));
		var user_password = ($("#register_form input[name='user_password']").attr('value'));
		//alert (user_nickname+', '+user_passwd);
		//return false;

		$.post("/port/register.user.php", {
				"user_email" : user_email,
				"user_nickname" : user_nickname,
				"user_password" : user_password
			}, function(data){
				if (data && data.result)
				{
					$('#register_error_message')
						.html('非常感谢您的注册！现在就可以占领你自己的小方块啦~')
						.css({'color':'green'});
					setTimeout(function(){
						$.unblockUI();
					}, 1200);
					$.growlUI('非常感谢您的注册！现在就可以占领你自己的小方块啦~'); 
				}
				else
				{
					$('#register_error_message')
						.html('登录名重名，注册失败，请换一个再试一下。')
						.css({'color':'red'});
				}
				$('#mini_map').css({
					'background-image':'url(port/minimap.php?' + Math.random() + ')'
				});
				draw_playground_tool_box();
			}, "json");
	}
	
	$("#register_form input[name='password']").keydown(function(e) {
		if(e.keyCode == 13) { // enter
			do_register();
		}
	});

	$('#register_form_submit').bind('click', function(){
		do_register();
	});

	show_register_form = function(s)
	{
		if (s)
		{
			$('#register_error_message')
				.html(s)
				.css({'color':'yellow'});
		}
		$.blockUI({ message: $('#register_form'), css:transparent_css_data});
	}

	
	blockui_message = function(msg, css)
	{
		if (!css)
			css = transparent_css_data;
		
		$.blockUI({
			message: msg,
			css: css
		});

		$('.blockUI').bind('click', function(event) {
			$.unblockUI();
			$('.blockUI').unbind('click');
		});
	}
		
	show_playground_help = function()
	{
		blockui_message($('#playground_help'));
	}
	
	$(window).bind('resize', function(){
		win_width = $(window).width();
		win_height = $(window).height();
		
		draw_map(0, 0);
	
	});

	// init map
	draw_map = function(offset_x, offset_y, nocache) {
		$('#play_ground_stage').css({
			left:0,
			top:0,
			width:win_width-1,
			height:win_height-1
		});

		if (nocache)
		{
			$('#mini_map').css({
				'background-image':'url(port/minimap.php?' + Math.random() + ')'
			});
			$('#play_ground_stage').html('');
		}
		
		var m_x = map_x-offset_x;
		var m_y = map_y-offset_y;

		var bx_start = Math.floor((m_x-win_width/2)/brick_size);
		var bx_end = Math.ceil((m_x+win_width/2)/brick_size);
		var by_start = Math.floor((m_y-win_height/2)/brick_size);
		var by_end = Math.ceil((m_y+win_height/2)/brick_size);
		
		//document.title = (by_end-by_start+1)*(bx_end-bx_start+1);

		for (var x=bx_start; x<=bx_end; x++)
		{
			for (var y=by_start; y<=by_end; y++)
			{
				var brick_id = 'brick_'+x+'_'+y;
				var cell = $("#"+brick_id)[0];
				var imUrl = '';

				if (!cell)
				{
					imUrl = 'port/getbrick.php?bx='+x+'&by='+y;
					cell = $('<div id='+brick_id+' class=cell></div>');
					cell.appendTo($('#play_ground_stage'));
					cell.css({'background-image':'url(' + imUrl + ')'});
				}

				$(cell).css({
					left:x*brick_size-map_x+win_width/2,
					top:y*brick_size-map_y+win_height/2
				});
			}
		}
		
		var cells = $('.cell');

		cells.each(function(index) {
			var dist_limit = 1000;
			
			var cell=$(cells[index]);
			var offset = cell.offset();
			
			var left = offset_x+offset.left;
			var right = left+cell_size;
			var top = offset_y+offset.top;
			var bottom = top+cell_size;
			
			if (left-win_width>dist_limit
				|| right<-dist_limit
				|| top<-dist_limit
				|| bottom-win_height>dist_limit)
			{
				$(cell).remove();
			}
			else
			{
				$(cell).css({
					left: left,
					top: top
				});
			}
		});

		if (mini_map_size>0)
		{
			$('#mini_map_navigator').css({
				left:(m_x-win_width/2)/cell_size/(map_size/mini_map_size),
				top:(m_y-win_height/2)/cell_size/(map_size/mini_map_size),
				width:(win_width)/cell_size/(map_size/mini_map_size),
				height:(win_height)/cell_size/(map_size/mini_map_size)
			});
		}
	}

	draw_map(0, 0);

	var handler_mini_map_timeout = null;
	var mini_map_mouse_down = false;
	$('#mini_map').bind('mousedown', function(event) {
		mini_map_mouse_down = true;
		var position = $(this).position();
		var x = event.pageX-position.left-5;
		var y = event.pageY-position.top-5;
		
		if (x<0 || y<0)return;
		//$('#play_ground_stage').html('');
		map_x = x*cell_size*(map_size/mini_map_size);
		map_y = y*cell_size*(map_size/mini_map_size);
		draw_map(0, 0);
	}).bind('mouseup', function( event ){
		mini_map_mouse_down = false;
/*	}).bind('mousemove', function( event ){
		if (mini_map_mouse_down)
		{
			var position = $(this).position();
			var x = event.pageX-position.left-5;
			var y = event.pageY-position.top-5;
			$('#play_ground_stage').html('');
			map_x = x*cell_size*(map_size/mini_map_size);
			map_y = y*cell_size*(map_size/mini_map_size);
	
			if (handler_mini_map_timeout!=null) clearTimeout(handler_mini_map_timeout);
				handler_mini_map_timeout = setTimeout(function(){
				draw_map(0, 0);
			}, 500);
		}*/
	});
	
	var dragStartX = 0;
	var dragStartY = 0;
	var selectorCellX = 0;
	var selectorCellY = 0;
	$('#play_ground_drag_layer').draggable({
		'start':function(event) {
			dragStartX = event.pageX;
			dragStartY = event.pageY;
		},
		'drag':function(event) {
			$('#play_ground_selector').hide();
			draw_map(event.pageX-dragStartX, event.pageY-dragStartY);
		},
		'stop':function(event) {
			map_x -= event.pageX-dragStartX;
			map_y -= event.pageY-dragStartY;
			draw_map(0, 0);

			// reset drag div
			$('#play_ground_drag_layer').css({
				left:0,
				top:0,
				width:win_width-1,
				height:win_height-1
			});
		}
	}).bind('mouseleave', function(event) {
		$('#play_ground_selector').hide();
	}).bind('mousemove', function(event) {

		var win_map_x = map_x-win_width/2;
		var win_map_y = map_y-win_height/2;
		var mouse_map_x = event.pageX+win_map_x;
		var mouse_map_y = event.pageY+win_map_y;
		var cell_map_x = Math.floor(mouse_map_x/cell_size);
		var cell_map_y = Math.floor(mouse_map_y/cell_size);
		var selector_x = cell_map_x*cell_size-win_map_x;
		var selector_y = cell_map_y*cell_size-win_map_y;

		$('#play_ground_selector').show();
		if (cell_map_x < 0 || cell_map_y < 0) {
			$('#play_ground_selector').css({
				left:-200
			});
		} else {
			$('#play_ground_selector').css({
				left:selector_x,
				top:selector_y
			});
		}
	}).bind('click', function(event) {
		var win_map_x = map_x-win_width/2;
		var win_map_y = map_y-win_height/2;
		var mouse_map_x = event.pageX+win_map_x;
		var mouse_map_y = event.pageY+win_map_y;
		selectorCellX = Math.floor(mouse_map_x/cell_size);
		selectorCellY = Math.floor(mouse_map_y/cell_size);
		
		//alert(selectorCellX+', '+selectorCellY);
		$.post("port/getitem.php", {
				"x" : selectorCellX,
				"y" : selectorCellY
			}, function(data){
				if (!data)
				{
					$.growlUI('服务器连接出现问题', '请您稍候再试。'); 
					return false;
				}
				
				if (data.item_image)
				{
					var win_url = '/item/'+data.item_id+'/';
					$('#image_show_url_detail_button').bind('click', function(){
						window.open(win_url);
						$(this).unbind('click');
					});
					blockui_message($('#image_show_url_outer'), {
							'background-image':'url('+data.item_image+')',
							cursor: 'default',
							width: data.item_image_width + 'px',
							height: data.item_image_height + 'px',
							left: ($(window).width() - data.item_image_width) /2 + 'px',
							top:  ($(window).height() - data.item_image_height) /2 + 'px',
							border: 'none',
							'text-align':'right'
					});
				}
				else if (data.result == 0)
				{
					$('#button-confirm-upload').hide();
					$('#file-list').html('');
					$.blockUI({ message: $('#upload_form'), css:transparent_css_data });
				}
				else
				{
					if (!$.cookie('user_logged'))
					{
						show_login_form('占领格子需要您先登录。还没有账号？<br>点<a href="javascript:{}" onclick="show_register_form()"><b>这里</b></a>填3项信息完成注册');
						return false;
					}

					if (data.last_item_x && data.last_item_y)
					{
						navigateToCellXY(data.last_item_x, data.last_item_y);
						$('#mini_map').css({
							'background-image':'url(port/minimap.php?' + Math.random() + ')'
						});

					}
					
					$.growlUI('不能在那里占领', data.message);
				}
			}, "json");

	});

	var uploader = new qq.FileUploader({
		element:$('#file-uploader')[0],
		params: {},
		allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
		debug: false,
		onSubmit: function(id, fileName){},
		onProgress: function(id, fileName, loaded, total){},
		onComplete: function(id, fileName, responseJSON){
			if (!responseJSON.success) return false;
			$('#file-list').html('');

			$("<input type=hidden name=item_image value='"+responseJSON.upname+"'>").appendTo($('#file-list'));
			var im=$("<span>"
				+"<img class=upload_image height=200 src='<?php echo ITEM_IMAGE_UPLOAD_BASE_URL."/"; ?>"+responseJSON.upname+"' /></span>");
			im.appendTo($('#file-list'));
			$(im).bind('click', function(e){
					$(this).remove();
				});
			$('#button-confirm-upload').show();

			$('.qq-upload-list').hide();
		},
		onCancel: function(id, fileName){},
		messages: {
		},
		showMessage: function(message){ alert(message); }
	});

	$('#button-confirm-upload').bind('click', function(event, delta) {
		
		$.post("port/additem.php", {
				"item_image" : $('input[name="item_image"]').val(),
				"item_x" : selectorCellX,
				"item_y" : selectorCellY
			}, function(data){
				$.unblockUI();
				//alert(data);
				if (data && data.result)
				{
					//reload the brick
					var x = Math.floor(selectorCellX/cell_count_of_brick_side);
					var y = Math.floor(selectorCellY/cell_count_of_brick_side);
					var brick_id = 'brick_'+x+'_'+y;
					var cell = $("#"+brick_id);
					if ($(cell))
					{
						imUrl = 'port/getbrick.php?bx='+x+'&by='+y+'&r='+Math.random();
						$(cell).css({'background-image':'url('+imUrl+')'});
					}
					
					$.growlUI('占领成功！', '如图片没有显示请刷新页面。'); 
				}
				else if (data && data.message)
				{
					$.growlUI('占领失败！', data.message); 
				}
			}, "json");
	});
});
